package top.syfy.jwt.jwtdemo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.syfy.jwt.jwtdemo.message.ReturnMessage;
import top.syfy.jwt.jwtdemo.message.ReturnMessageUtil;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理类, 通过 @RestControllerAdvice 使用 AOP 编程原理将通知定义在表现层, 只要表现层有异常都可以被本处理类监听到
 *
 * @author syfy
 * @date 2021/03/05
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = Exception.class)
	public ReturnMessage<Object> exceptionHandler(HttpServletResponse response, Exception e) {
		response.setCharacterEncoding("UTF-8");
		if (e instanceof CustomerException) {
			CustomerException ce = (CustomerException) e;
			logger.error("CustomerException : {}", (Object) e.getStackTrace());
			return ReturnMessageUtil.error(ce.getCode(), ce.getMessage());
		} else {
			logger.error("Unknown Exception : {}", (Object) e.getStackTrace());
			return ReturnMessageUtil.error(-1, "未知异常: " + e.getMessage());
		}
	}


}
